package com.tongcao.cn.listener.nacos;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.annotation.NacosConfigListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Properties;

/**
 * @author:tongcao
 * @since:2019/7/25 14:23
 * Description:Nacos 监听器
 */

@Configuration
public class SimpleNacosConfigListener {

    private static final Logger logger = LoggerFactory.getLogger(SimpleNacosConfigListener.class);

    public static final String PROPERTIES_DATA_ID = "example";

    public static final String DATA_ID = "properties-data-id";

    @NacosInjected
    private ConfigService configService;

    @PostConstruct
    public void init() throws Exception {
//        // Build Properties Content
//        StringBuilder builder = new StringBuilder();
//        builder.append("user.id = 1");
//        builder.append(SystemUtils.LINE_SEPARATOR);
//        builder.append("user.name = mercyblitz");
//        builder.append(SystemUtils.LINE_SEPARATOR);
//        builder.append("user.github = https://github.com/mercyblitz");
//        configService.publishConfig(PROPERTIES_DATA_ID, DEFAULT_GROUP, builder.toString());
    }

    @NacosConfigListener(dataId = PROPERTIES_DATA_ID)
    public void onReceived(String value) {
        logger.info("onReceived(String) : {}", value);
    }

    @NacosConfigListener(dataId = PROPERTIES_DATA_ID)
    public void onReceived(Properties value) {
        logger.info("onReceived(Properties) : {}", value);
    }

    /**
     * 测试timeout
     * @param value
     * @throws InterruptedException
     */
    @NacosConfigListener(dataId = DATA_ID, timeout = 100)
    public void onReceivedWithTimeout(String value) throws InterruptedException {
        Thread.sleep(200);
        logger.info("onReceivedWithTimeout(String) : {}", value); // Never executes
    }

    @NacosConfigListener(dataId = DATA_ID, timeout = 100)
    public void onReceivedWithoutTimeout(String value) throws InterruptedException {
        Thread.sleep(50);
        logger.info("onReceivedWithoutTimeout(String) : {}", value);
    }
}